<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-3.dtd">
<html xmlns="http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd" xmlns:th="http://www.thymeleaf.org">
<!-- <!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd"> -->
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
		<meta charset="UTF-8"/>
		<meta http-equiv="CACHE-CONTROL" content="NO-CACHE" />
		<meta http-equiv="EXPIRES" content="Mon, 01 Jan 2000 00:00:01 GMT" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
		<title th:text="${title}">UGate Mobile (prototype)</title>
		<meta name="description" content="UGate Mobile Interface"/>
		<meta name="keywords" content="ugate, ugate mobile"/>
		<meta name="author" content=""/>
		<meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1, user-scalable=no"/>
<!-- 		<link rel="icon" href="logo16x16.png"/> -->
<!-- 		<link rel="apple-touch-icon" size="144x144" href="logo128x128.png"/> -->
<!-- 		<link rel="apple-touch-icon" size="114x114" href="logo128x128.png"/> -->
<!-- 		<link rel="apple-touch-icon" size="72x72"   href="logo64x64.png"/> -->
<!-- 		<link rel="apple-touch-icon" size="57x57"   href="logo64x64.png"/> -->
<!-- 		<link rel="apple-touch-icon" href="logo64x64.png"/> -->
		<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
		<script th:inline="javascript" type="text/javascript">
		/*<![CDATA[*/
		    var AJAX_UPDATE_URL = /*[[${ajaxUpdateUrl}]]*/ "";
		    var WEB_SOCKET_URI = /*[[${webSocketUri}]]*/ "";
			var COMMAND = "command";
			var ACTION = "action";
			var ACT_CONNECT = "connect";
			var RN_ID = "id";
			var defaultLoadingMsg = "Please Wait...";
		/*]]>*/
		</script>
		<script type="text/javascript">
		/*<![CDATA[*/
			var ws, wsm = false, wsc = 0, fc;
			// converts form data into JSON object
			(function($) {
				$.fn.serializeFormJSON = function() {
					var o = {};
					var a = this.serializeArray();
					$.each(a, function() {
						if (o[this.name] !== undefined) {
							if (!o[this.name].push) {
								o[this.name] = [ o[this.name] ];
							}
							o[this.name].push(this.value || '');
						} else {
							o[this.name] = this.value || '';
						}
					});
					return o;
				};
			})(jQuery);
			$(document).bind("mobileinit", function() {
				$.mobile.loader.prototype.options.textVisible = true;
				$.mobile.loader.prototype.options.textonly = false;
				//$.mobile.ajaxEnabled = false;
				$.mobile.loadingMessage = defaultLoadingMsg;
			});
			$(document).bind("pagebeforeload", function() {
				var msgo = $('#feedbackMessage');
				var msg = msgo ? msgo.text() : null;
				$.mobile.loadingMessage = msg ? msg : 'Loading...';
			});
			$(document).bind(
					"pageloadfailed",
					function(event, data) {
						// show error content from HTTP 500 error page
						var msg = $(data.xhr.responseText)
								.find("#errorContent").html();
						$.mobile.pageLoadErrorMessage = msg ? msg
								: data.errorThrown;
					});
			$(document).bind("pageshow", function() {
				openWebSocket();
			});
			// WebSocket
			$(document).ready(function() {
				fc = $('[data-role="footer"]').html();
			    $('select').each(function() {
			        this.oldValue = $(this).val();
			    });
			});
			function openWebSocket() {
				try {
					if (!WEB_SOCKET_URI) {
						return;
					}
					// 0 = not connected, 1 = connected, 2 = closing, 3 = closed
					if (!ws || ws.readyState === undefined || ws.readyState > 1) {
						updateFooterStatus('gear');
						// http://jquerymobile.com/test/docs/api/methods.html
						var url = $.mobile.path.parseUrl(window.location.href);
						var wsp = url.protocol == "http:" ? "ws" : "wss";
						ws = new WebSocket(wsp + "://" + url.host + WEB_SOCKET_URI);
						ws.onopen = function(event) {
							//hideMessage();
							wsc = 0;
							wsm = true;
							updateFooterStatus('check');
						};
						ws.onmessage = function(event) {
							//alert(event.data);
							updateValues(jQuery.parseJSON(event.data));
						};
						ws.onclose = function(event) {
							updateFooterStatus('alert');
							wsc++;
							if (wsm) {
								//showMessage('Attempting ' + wsc + ' to reconnect to server');
							}
							setTimeout(openWebSocket, 3000);
						};
					} else if (ws && ws.readyState == 1) {
						//alert(ws);
						updateFooterStatus('check');
					}
				} catch (e) {
					//alert('Unable to connect to server for real-time updates ' + e);
					updateFooterStatus('delete');
				}
			}
			// update all form elements that have the same name as the JSON attribute name 
			// when the form contains an element with a name == id and the value of that 
			// element == the JSON id
			function updateValues(json) {
				try {
					//alert(json);
					if (json && json.id) {
						$('form').each(function() {
							var form = $(this);
							var id = form.find('input[name="id"]');
							//alert('id.val(): ' + id.val() + ' json.id: ' + json.id);
							if (id && id.val() == json.id) {
								var rnrId = form.find('input[name="remoteNodeReadings"]');
								if (rnrId && json.remoteNodeReadings) {
									//alert('RNR ID: ' + rnrId.val() + ' JSON RNR ID: ' + json.remoteNodeReadings.id);
									updateNameValues(form, json.remoteNodeReadings);
								} else {
									//alert('RN ID: ' + id.val() + ' JSON RN ID: ' + json.id);
									updateNameValues(form, json);
								}
							}
						});
					}
				} catch (e) {
					alert("Unable to update UI (error: " + e
							+ ") with data from\n\n" + event.data);
					refreshPage();
				}
			}
			function updateNameValues(form, json) {
				$.each(json, function(name, value) {
					var f = form.find('input[name="' + name + '"]');
					//alert('f: ' + (f ? f.attr("name") : 'N/A'));
					if (f && f.attr("name")) {
						//alert('f: ' + f.attr("name") + ' v: ' + f.val() + ' nv: ' + value);
						f.val(value);
						if (typeof f.slider == 'function') {
							try {f.slider('refresh');} catch (e) {}
						}
					}
				});
			}
			// AJAX calls
			function rnConnect(iconId, rnId, waitMessage) {
				showMessage(waitMessage);
				try {
					// TODO : Once https://github.com/jquery/jquery-mobile/issues/4317 is released the proper update can be made to the data-icon change
					var isel = '#' + iconId;
					ajaxGo(null, rnId, ACTION + '=' + ACT_CONNECT, function(
							data) {
						hideMessage();
						updateIcon(isel, 'check');
					}, function (xhr, status, thrown) {
						hideMessage();
						updateIcon(isel, 'alert');
						ajaxGoError(xhr, status, thrown);
					});
				} catch (e) {
					showMessage(e.message);
				}
				//alert('gone');
			}
			// executes a command
			function exeCommand(command, formId, sourceName) {
				try {
					var form = null;
					var src = null;
					var ov = null;
					if (formId && sourceName) {
						form = $('#' + formId);
						src = form.find('[name="' + sourceName + '"]');
						ov = src.oldValue;
						src.oldValue = src.val();
					}
					var element = $('<input>').attr({
						type : 'hidden',
						id : command,
						name : command,
						value : command
					});
					ajaxGo(element, null, null, null, function(xhr, status, thrown) {
						if (form && src && src.attr("name")) {
							//alert('ov: ' + ov + ' src.defaultValue: ' + src.defaultValue + ' src.oldValue: ' + src.oldValue);
							src.val(ov);
							if (typeof src.slider == 'function') {
								try {src.slider('refresh');} catch (e) {}
							}
						}
						ajaxGoError(xhr, status, thrown);
					});
				} catch (e) {
					showMessage(e.message, 10000, true);
				}
			}
			// when a slider stops sliding submit form data
			$(document).bind("pageinit", function() {
				$(".ui-slider-input, .ui-slider-switch").each(function() {
					$(this).on('slidestop', function(event) {
						ajaxGo(this);
					});
				});
			});
			function ajaxGo(element, rnId, params, successFunc, errorFunc) {
				var httpMeth = "POST";
				var form;
				if (element && !element.form) {
					form = $('#rnCommandForm');
					var cmd = form.find('input[name="' + COMMAND + '"]');
					cmd.val($(element).attr('id'));
				} else if (element) {
					form = $(element.form);
					httpMeth = "PUT";
				}
				var jsonObj = form ? form.serializeFormJSON() : null;
				if (jsonObj || params) {
					var rnIdData = rnId ? RN_ID + '=' + rnId + '&' : '';
					var jsonData = rnIdData + (jsonObj ? $.param(jsonObj) : '')
							+ (params ? '&' + params : '');
					//alert(jsonData);
					var sf = (successFunc ? successFunc : ajaxGoSuccess);
					var ef = (errorFunc ? errorFunc : ajaxGoError);
					$.ajax({
						type : httpMeth,
						url : AJAX_UPDATE_URL,
						data : jsonData,
						cache : false,
						dataType : "xml",
						success : sf,
						error : ef
					});
				}
			}
			function ajaxGoError(xhr, status, thrown) {
				showMessage(status + ': ' + thrown, 5000, true);
			}
			function ajaxGoSuccess(data) {
				//showMessage('Data submitting. Result: ' + data, 5000);
				hideMessage();
			}
			// Messages
			function showMessage(msg, timeout, isError) {
				$.mobile.loadingMessage = msg;
				$.mobile.loadingMessageTheme = isError ? 'e' : 'a';
				$.mobile.loading('show');
				if (timeout) {
					setTimeout(function() {
						hideMessage();
						$.mobile.loadingMessageTheme = 'a';
					}, timeout);
				}
			}
			function hideMessage() {
				$.mobile.loading('hide');
				$.mobile.loadingMessage = defaultLoadingMsg;
			}
			function refreshPage() {
				$.mobile.changePage(window.location.href, {
					allowSamePageTransition : true,
					transition : 'none',
					showLoadMsg : false,
					reloadPage : true
				});
			}
			function updateIcon(iconSelector, iconName) {
				var b = $(iconSelector);
				b.buttonMarkup({
					icon : iconName
				});
				/*
				try {
					b.attr('data-icon', iconName).trigger('refresh');
					b.button('refresh');
				} catch (e) {
					try {
						b.attr('data-icon', iconName);
						b.button('create');
					} catch (e2) {
						b.buttonMarkup({ icon: iconName });
						throw 'ERROR 1: ' + e + '\n\nERROR 2: ' + e2;
					}
				}
				//alert('data-icon: ' + b.attr('data-icon') + ' data-theme: ' + b.attr('data-theme'));
				 */
			}
			function updateFooterStatus(iconName) {
				//updateIcon('#wsStatus', iconName);
				var footer = $('[data-role="footer"]');
				var html = fc.replace(/(<a\s+.*?data-icon=").*?(".*)/gi, "$1"
						+ iconName + "$2");
				//alert(html);
				footer.html(html).trigger('create');
			}
			/*]]>*/
		</script>
		<script src="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
	</head>
	<body>
		<div data-role="page" id="mainPage" data-theme="a" data-swatch="a" data-dom-cache="false">
			<div class="ui-header ui-bar-a" data-swatch="a" data-theme="a"
				data-form="ui-bar-a" data-role="header" role="banner" data-position="fixed">
				<a class="ui-btn-left ui-btn ui-btn-icon-notext ui-btn-corner-all ui-shadow ui-btn-up-a"
					data-iconpos="notext" data-theme="a" data-role="button"
					data-icon="home" th:title="${title}" th:href="@{/}" title=" Home " href="/base.html">
					<span class="ui-btn-inner ui-btn-corner-all">
						<span class="ui-btn-text" th:text="${title}">Title (prototype)</span>
						<span data-form="ui-icon" class="ui-icon ui-icon-home ui-icon-shadow">&nbsp;</span>
				</span>
				</a>
				<h1 class="ui-title" tabindex="0" role="heading" aria-level="1">
					<span th:text="${header}" id="headerLabel">Header (prototype)</span>
				</h1>
<!-- 				<a -->
<!-- 					class="ui-btn-right ui-btn ui-btn-icon-notext ui-btn-corner-all ui-shadow ui-btn-up-a" -->
<!-- 					data-iconpos="notext" data-theme="a" data-role="button" -->
<!-- 					data-icon="grid" title=" Navigation "> <span -->
<!-- 					class="ui-btn-inner ui-btn-corner-all"> <span -->
<!-- 						class="ui-btn-text"> Navigation </span> <span data-form="ui-icon" -->
<!-- 						class="ui-icon ui-icon-grid ui-icon-shadow"></span> -->
<!-- 				</span> -->
<!-- 				</a> -->
				<a th:href="@{/logout}" th:if="${remoteUser}" href="/login.html" 
					data-theme="b" data-iconpos="right" data-icon="arrow-r"  
					class="ui-btn-right ui-btn ui-shadow ui-btn-corner-all ui-btn-icon-right ui-btn-up-b" 
					data-corners="true" data-shadow="true" data-iconshadow="true" data-wrapperels="span"
					data-transition="flip">
					<span class="ui-btn-inner ui-btn-corner-all">
						<span class="ui-btn-text" th:text="#{logout}">Logout (prototype)</span>
						<span class="ui-icon ui-icon-arrow-r ui-icon-shadow">&nbsp;</span>
					</span>
				</a>
			</div>
			<div th:include="${content} :: content" id="content" data-role="content">
				<script type="text/javascript">
				/*<![CDATA[*/
					// prototype content replaced by fragment on server
					var pp = 'login.html';
					var hashes = window.location.href.slice(
							window.location.href.indexOf('?') + 1).split('&');
					for (var i = 0; i < hashes.length; i++) {
						var hash = hashes[i].split('=');
						if (hash[0] == 'page' && hash[1]) {
							pp = hash[1] + '.html';
							break;
						}
					}
					$('#content').load(pp, function() {
						//alert('prototype load was performed.');
					});
				/*]]>*/
				</script>
			</div>
			<div data-role="footer" data-theme="a" data-position="fixed" 
				style="vertical-align: middle; padding: 0;">
				<div data-role="navbar" data-iconpos="top">
					<ul>
						<li th:title="#{app.footer.updates.inidcator}" title="Live Updates Indicator" >
							<a th:text="${footer}" id="wsStatus" href="#" class="ui-disabled" style="opacity: 1;"
								data-mini="true" data-inline="true" data-role="button" data-theme="a" data-icon="alert" data-iconpos="right">
								Footer (prototype)
							</a>
						</li>
					</ul>
				</div>
<!-- 			<div th:title="#{app.footer.updates.inidcator}" title="Live Updates Indicator" data-role="footer" data-theme="a" data-position="fixed"  -->
<!-- 				style="vertical-align: middle; padding: 0;"> -->
<!-- 				<h4 align="center" style="margin-top: 0; margin-bottom: 0;"> -->
<!-- 					<a th:text="${footer}" id="wsStatus" href="#" class="ui-disabled" style="opacity: 1;" -->
<!-- 						data-mini="true" data-inline="true" data-role="button" data-theme="a" data-icon="alert" data-iconpos="right"> -->
<!-- 						Footer (prototype) -->
<!-- 					</a> -->
<!-- 				</h4> -->
<!-- 			</div> -->
			</div>
		</div>
		<div id="feedbackMessage" style="display:none;">Loading...</div>
	</body>
</html>